package org.example.judge_comment.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.example.judge_comment.common.RequestCommentParams;
import org.example.judge_comment.service.CommentLikeService;
import org.example.judge_comment.service.CommentService;
import org.example.judge_comment.service.MailService;
import org.example.judge_common.annotation.AuthAnnotation;
import org.example.judge_common.entity.PageResult;
import org.example.judge_common.entity.ResponseResult;
import org.example.judge_common.util.MyUtils;
import org.example.judge_pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@CrossOrigin
@Slf4j
@RequestMapping("/comment")
public class CommentController {


    @Qualifier("MailServiceImpl")
    @Autowired
    private MailService mailService;

    @Qualifier("CommentServiceImpl")
    @Autowired
    private CommentService commentService;

    @Qualifier("CommentLikeServiceImpl")
    @Autowired
    private CommentLikeService commentLikeService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/search")
    public ResponseResult search(RequestCommentParams params,HttpServletRequest request){
        User loginUser = (User) request.getAttribute("loginUser");
        if(!Auth.isAdmin(loginUser))params.setStatus(0);  //非管理员只能访问未被封禁的
        if(params.getPage()==null)params.setPage(1);
        if (params.getSize()==null) {
            params.setSize(10);
        }
        PageResult<Comment> res = commentService.search(params);
        return ResponseResult.success().setData(res);
    }

    @PostMapping("/save")
    @AuthAnnotation({Auth.CLIENT})
    public ResponseResult save(HttpServletRequest request, @RequestBody Comment comment){
        User loginUser = (User) request.getAttribute("loginUser");
        comment.setUserId(loginUser.getId());
        comment.setIp(request.getLocalAddr());
        boolean save = commentService.save(comment);
        return ResponseResult.success().setData(comment);
    }
    @PutMapping("/update")
    @AuthAnnotation({Auth.CLIENT})
    public ResponseResult update(@RequestBody Comment comment,HttpServletRequest request){
        User loginUser = (User) request.getAttribute("loginUser");
        if(!Auth.isAdmin(loginUser)&&!loginUser.getId().equals(comment.getUserId())) {
            return ResponseResult.unAuditor();
        }
        if(comment.getStatus()!=null&&comment.getStatus()==1){  //封禁
            //提醒用户
            Mail mail = new Mail();
            mail.setUserId("1");
//            String title = null;
//            if(comment.getType()==0)comment.getTitle();
//            else title = comment.getText().length()<=10?comment.getText():comment.getText().substring(0,10);
            mail.setText("你的 ["+comment.getTitle()+"](/#/main/comment/detail/"+comment.getId()+") 已被 "+loginUser.getUsername()+" 封禁");
            mail.setTo(loginUser.getId());
            mailService.save(mail);
        }
        return ResponseResult.success().setData(commentService.updateById(comment));
    }
    @DeleteMapping("/delete/{id}")
    @AuthAnnotation({Auth.CLIENT})
    public ResponseResult delete(@PathVariable("id")String id,HttpServletRequest request){
        Comment byId = commentService.getById(id);
        if(byId==null)return ResponseResult.fail("该帖子/评论不存在");
        User loginUser = (User) request.getAttribute("loginUser");
        if(!Auth.isAdmin(loginUser)&&!loginUser.getId().equals(byId.getUserId())) {
            return ResponseResult.unAuditor();
        }
        boolean b = commentService.removeById(id);
        if(b){
            log.info("评论/帖子：{}:{}被用户：{}删除",byId.getId(),byId.getTitle(),loginUser.getUsername());

            //提醒用户
            Mail mail = new Mail();
            mail.setUserId("1");
            String title = null;
            if(byId.getType()==0)byId.getTitle();
            else title = byId.getText().length()<=50?byId.getText():byId.getText().substring(0,50);
            mail.setText("你的 ["+title+"](/#/main/comment/detail/"+byId.getId()+") 已被 "+loginUser.getUsername()+" 删除");
            mail.setTo(loginUser.getId());
            mailService.save(mail);
        }
        return ResponseResult.success().setData(b);
    }
    @PostMapping("/detail/{id}")
    public ResponseResult detail(@PathVariable("id")String id,HttpServletRequest request){

        Comment byId = commentService.getById(id);

        if(byId==null) {
            byId = new Comment();byId.setId(id);
            return ResponseResult.NotData().setData(byId);
        }
        User loginUser = (User) request.getAttribute("loginUser");
        if(byId.getStatus()!=0&&!Auth.isAdmin(loginUser)) {

            byId.setText(null);
            byId.setTitle(null);
            return ResponseResult.NotData("该帖子已被封禁").setData(byId);
        }
        return ResponseResult.success().setData(byId);
    }

    /**
     * 获取其根节点，type==0
     * @param id
     * @param request
     * @return
     */
    @PostMapping("/root/{id}")
    public ResponseResult getGrandDetail(@PathVariable("id")String id,HttpServletRequest request){

        QueryWrapper<Comment> warp = new QueryWrapper<Comment>().eq("`id`", id);

        Comment byId = commentService.getOne(warp);
        if(byId==null)return ResponseResult.NotData();
        while(byId.getType()!=0){
            warp.clear();
            warp.eq("`id`",byId.getFatherId());
            byId = commentService.getOne(warp);
            if(byId==null){
                return ResponseResult.success();
            }
        }
        User loginUser = (User) request.getAttribute("loginUser");
        if(byId.getStatus()!=0&&!Auth.isAdmin(loginUser)) {
            byId.setTitle("该帖子已被封禁...");
            byId.setText("该帖子内容已被封禁...");
            return ResponseResult.success();
        }
        return ResponseResult.success().setData(byId);
    }

    /**
     * 点赞/取消
     * @param commentId
     * @param request
     * @return
     */
    @PostMapping("like/{id}")
    @AuthAnnotation({Auth.CLIENT})
    public ResponseResult likeOrRemove(@PathVariable("id")String commentId,HttpServletRequest request){

        User loginUser = (User) request.getAttribute("loginUser");
        Comment byId = commentService.getById(commentId);
        if(commentLikeService.isLike(commentId,loginUser.getId())!=null){  //有则取消
            commentLikeService.remove(commentId,loginUser.getId());
            byId.setLikeSum(byId.getLikeSum()-1);
        }else{
            //添加
            CommentLike commentLike = new CommentLike();
            commentLike.setCommentId(commentId);
            commentLike.setUserId(loginUser.getId());
            commentLikeService.save(commentLike);
            byId.setLikeSum(byId.getLikeSum()+1);
        }
        //更新到数据库
        commentService.updateById(byId);
        return ResponseResult.success();
    }

    /**
     * 获取用户的新消息
     * @param request
     * @return
     */
    @PostMapping("/isNew")
    public ResponseResult isNew(HttpServletRequest request){
        User loginUser = (User) request.getAttribute("loginUser");
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();

        //查询评论总信息
        wrapper.eq("type",1).eq("title",loginUser.getId());
        int commentCount = commentService.count(wrapper); //评论我的

        //获取老的未读信息数
        int commentCountOld = 0;
        Object o = redisTemplate.opsForValue().get(loginUser.getId() + "_CommentCount");
//        redisTemplate.opsForValue().set(loginUser.getId() + "_CommentCount",commentCount);
        if(o!=null){
            commentCountOld = Integer.parseInt(o.toString());
            commentCount -= commentCountOld;
        }

        //查询回复的信息数
        wrapper.clear();
        wrapper.eq("type",2).eq("title",loginUser.getId());
        int replyCount = commentService.count(wrapper);

        //获取老的未读信息数
        int replyCountOld = 0;
        o = redisTemplate.opsForValue().get(loginUser.getId() + "_ReplyCount");
//        redisTemplate.opsForValue().set(loginUser.getId() + "_ReplyCount",replyCount);
        if(o!=null){
            replyCountOld = Integer.parseInt(o.toString());
            replyCount -=replyCountOld;
        }
        QueryWrapper<Mail> mailWrapper = new QueryWrapper<>();

        //查询系统的未读信息
        mailWrapper.eq("`to`",loginUser.getId()).eq("user_id","1").eq("`read`",0);
        int systemCount = mailService.count(mailWrapper);

        //查询私信的未读信息
        mailWrapper.clear();
        mailWrapper.eq("`to`",loginUser.getId()).ne("user_id","1").eq("`read`",0);
        int userCount = mailService.count(mailWrapper);
        int[] res = {systemCount,commentCount,replyCount,userCount};
        return ResponseResult.success().setData(res);
    }

    /**
     * 标记已读
     * @param name  缓存后缀名
     * @param count
     * @param request
     * @return
     */
    @PostMapping("/read")
    public ResponseResult read(String name,Integer count,HttpServletRequest request){
        if(MyUtils.isEmpty(name))return ResponseResult.NotData();
        User loginUser = (User) request.getAttribute("loginUser");
        redisTemplate.opsForValue().set(loginUser.getId() + name,count);
        return ResponseResult.success();
    }

}
